package uk.co.richardwkirk.parkrun.news;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class NewsFeedHandler implements ContentHandler {

	StringBuilder chars = new StringBuilder();

	NewsFeed newsFeed = null;
	NewsItem newsItem = null;
	
	public NewsFeedHandler(NewsFeed nf) {
		this.newsFeed = nf;
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		chars.append(new String(ch, start, length));
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		// HTML content under a content:encoded tag
		if (qName.equals("content:encoded") || localName.equals("encoded")) {
			newsItem.appendHtmlContent(chars.toString());
		}
		else if (qName.equals("title")) {
			if (newsItem == null) {
				newsFeed.setTitle(chars.toString());
			}
			else {
				newsItem.setTitle(chars.toString());
			}
		}
		else if (qName.equals("link")) {
			if (newsItem == null) {
				newsFeed.setLink(chars.toString());
			}
			else {
				newsItem.setLink(chars.toString());
			}
		}
		else if (qName.equals("item")) {
			// Completed the current item. Add it to the news feed
			// and start building the next item.
			newsFeed.addItem(newsItem);
			newsItem = null;
		}
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processingInstruction(String target, String data) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setDocumentLocator(Locator locator) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void skippedEntity(String name) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
		chars = new StringBuilder();
		
		// Start a new news item
		if (qName.equals("item")) {
			newsItem = new NewsItem();
		}
	}

	@Override
	public void startPrefixMapping(String prefix, String uri) throws SAXException {
		// TODO Auto-generated method stub
		
	}
	
}

